package com.bluedot.www.framework.mvc.utils;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author He Peng
 * @version 1.0
 * @date 2021/8/22 10:28
 */
public class FileCopyUtil {

    /**
     * 复制字节时，默认的缓冲区大小
     */
    private static final int BUFFER_SIZE = 4369;


    /**
     * 将给定InputStream的内容复制到给定OutputStream。完成时关闭两个流。
     *
     * @param in:  输入流
     * @param out: 输出入
     * @return int
     * @author He Peng
     * @date 2021/8/22 10:44
     */
    public static int copy(InputStream in, OutputStream out) throws IOException {
        Assert.notNull(in, "No InputStream specified");
        Assert.notNull(out, "No OutputStream specified");

        try {
            int byteCount = 0;
            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
                byteCount += bytesRead;
            }
            out.flush();
            return byteCount;
        } finally {
            close(in);
            close(out);
        }
    }


    /**
     * 尝试关闭提供的Closeable，静默地接受任何异常
     *
     * @param closeable: 可被关闭的资源
     * @author He Peng
     * @date 2021/8/22 10:42
     */
    private static void close(Closeable closeable) {
        try {
            closeable.close();
        } catch (IOException ex) {
            // ignore
        }
    }

}
